// javaScript for jcvp_web
var ws;
var g_mouse_is_down = false;
var g_point_show = 0;
var g_point = {x:0, y:0};
var g_rect = {x:0, y:0, w:0, h:0};
var g_img_scaling = 1.5;
var server_ip = window.location.host;
var g_rec_mediaRecorder = null;
let g_rec_chunks = [];

function setupWebSocket()
{
	if ("WebSocket" in window) {
		var canvas = document.getElementById('player');
		var ctx = canvas.getContext('2d');
		ws = new WebSocket('ws://'+server_ip+'/ws/video');
		ws.onopen = function(event) {
			console.log('on opened!');
			ws.send('{"type":"echo", "key":"connected"}');
		};
		ws.onmessage = function(event) {
			if (typeof (event.data) === 'string') {
				json_data_parse(event.data);
			} else {
				var img = new Image();
				img.onload = function() {
					canvas.width = img.width;
					canvas.height = img.height;
					ctx.drawImage(img, 0, 0);
					draw_osd_to_ctx(ctx); //叠加前端OSD
					draw_mouse_to_ctx(ctx); //绘制鼠标事件
				}
				img.src = URL.createObjectURL(event.data);
			}
		};
		ws.onclose = function(event) {
			console.log('on closed!');
		};
		ws.onerror = function(error) {
			console.error('on WebSocket error:', error);
		};
	} else {
		alert("您的浏览器不支持 WebSocket!");
	}
}

function test_send()
{
	ws.send('{"type":"echo", "key":"value"}');
}

function ws_send_rect_sel()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "rect", 
			rect: {
				x: (g_rect.x * g_img_scaling),
				y: (g_rect.y * g_img_scaling),
				w: (g_rect.w * g_img_scaling),
				h: (g_rect.h * g_img_scaling)
			}
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function ws_send_point_sel()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "point",
			point: {
				x: (g_rect.x * g_img_scaling),
				y: (g_rect.y * g_img_scaling)
			}
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function canvas_init_draw()
{
	var canvas = document.getElementById('player');
	var ctx = canvas.getContext('2d');
	//封面绘制
	ctx.fillStyle = "rgba(0, 0, 0, 1.0)";
	ctx.fillRect(0, 0, canvas.width, canvas.height);
	ctx.fillStyle = "rgba(200, 200, 200, 0.8)";
	ctx.beginPath();
	ctx.moveTo(canvas.width/2-40, canvas.height/2-40);
	ctx.lineTo(canvas.width/2+40, canvas.height/2);
	ctx.lineTo(canvas.width/2-40, canvas.height/2+40);
	ctx.closePath();
	ctx.fill();
	// 鼠标按下事件
	canvas.addEventListener('mousedown', function(e) {
		g_mouse_is_down = true;
		g_rect.x = e.pageX - canvas.offsetLeft;
		g_rect.y = e.pageY - canvas.offsetTop;
	});
	// 鼠标移动事件
	canvas.addEventListener('mousemove', function(e) {
		if (g_mouse_is_down) {
			g_rect.w = (e.pageX - canvas.offsetLeft) - g_rect.x;
			g_rect.h = (e.pageY - canvas.offsetTop) - g_rect.y;
		}
	});
	// 鼠标抬起事件
	canvas.addEventListener('mouseup', function(e) {
		g_mouse_is_down = false;
		if (Math.abs(g_rect.w) > 3 && Math.abs(g_rect.h) > 3) {
			console.log("Mouse box selsect Rect: [" + g_rect.x + "," + g_rect.y + ", " + g_rect.w + "," + g_rect.h + "]");
			ws_send_rect_sel();
		}
		g_rect.w = 0;
		g_rect.h = 0;
	});
	//鼠标单击事件
	canvas.addEventListener('click', function(e) {
		if (ws === undefined || ws === null) {
			var m_x = e.pageX - canvas.offsetLeft;
			var m_y = e.pageY - canvas.offsetTop;
			if (m_x > (canvas.width/2-40)  && m_x < (canvas.width/2+40) && m_y > (canvas.height/2-40) && m_y < (canvas.height/2+40)) {
				setupWebSocket();
			}
		}
	});
	//鼠标双击事件
	canvas.addEventListener('dblclick', function(e) {
		g_point.x = (e.pageX - canvas.offsetLeft);
		g_point.y = (e.pageY - canvas.offsetTop);
		g_point_show = 20;
		console.log("Mouse double click at: [" + g_point.x + "," + g_point.y + "]");
		ws_send_point_sel();
	});
}

//叠加前端OSD信息
function draw_osd_to_ctx(context)
{
}

//鼠标绘制
function draw_mouse_to_ctx(context)
{
	if (Math.abs(g_rect.w) > 3 && Math.abs(g_rect.h) > 3) {
		context.lineWidth = 3;
		context.strokeStyle = "rgba(0, 0, 255, 0.8)";
		context.strokeRect(g_rect.x, g_rect.y, g_rect.w, g_rect.h);
	}
	if (g_point_show > 0) {
		context.lineWidth = 3;
		context.strokeStyle = "rgba(0, 0, 255, 0.8)";
		context.arc(g_point.x, g_point.y, 5, 0, 2*Math.PI);
		context.stroke();
		g_point_show--;
	}
}

function on_player_record()
{
	if (g_rec_mediaRecorder === null) {
		g_rec_mediaRecorder = new MediaRecorder(document.getElementById('player').captureStream(), {mimeType: 'video/webm'});
		g_rec_mediaRecorder.ondataavailable = event => {
			if (event.data && event.data.size > 0) {
				g_rec_chunks.push(event.data);
			}
		};
		g_rec_mediaRecorder.onstop = () => {
			const blob = new Blob(g_rec_chunks, { type: 'video/webm' });
			g_rec_chunks = [];
			var cur_time = new Date();
			const url = URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = 'jcvp_player_record_'+cur_time.toLocaleString()+'.webm';
			a.click();
			URL.revokeObjectURL(url);
		};
	}
	if (g_rec_mediaRecorder.state === 'recording') {
		g_rec_mediaRecorder.stop();
		document.getElementById('jc_player_record').textContent = 'REC';
		document.getElementById('jc_player_record').style.backgroundColor = 'red';
		document.getElementById('js_player_record').textContent = 0;
		document.getElementById('js_player_record').style.display = 'none';
	} else {
		g_rec_mediaRecorder.start();
		document.getElementById('jc_player_record').textContent = 'STOP';
		document.getElementById('jc_player_record').style.backgroundColor = 'gray';
		document.getElementById('js_player_record').style.display = 'inline';
		setTimeout(player_rec_state_update, 1000);
	}
}
function player_rec_state_update()
{
	document.getElementById('js_player_record').textContent = parseInt(document.getElementById('js_player_record').textContent) + 1;
	if (g_rec_mediaRecorder.state === 'recording') {
		setTimeout(player_rec_state_update, 1000);
	}
}

function jc_nfs_mount()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "data_ctl",
			cmd: "nfs_mount",
			dir: document.getElementById('jc_nfs_dir').value,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function record_raw_send()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "data_ctl",
			cmd: "rec_raw",
			frame_num: 1000,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);

		document.getElementById('jc_record_start').disabled = true;
		document.getElementById('jc_record_start').style.backgroundColor = 'gray';
	}
}

function json_data_parse(json_str)
{
	var json_obj = JSON.parse(json_str);

	if (undefined != json_obj.date) {
		document.getElementById('date_val').textContent = json_obj.date;
	}
	if (undefined != json_obj.time) {
		document.getElementById('time_val').textContent = json_obj.time;
	}
	if (undefined != json_obj.record_state) {
		document.getElementById('js_record_state').textContent = json_obj.record_state.cur + '/' + json_obj.record_state.all;
		if (json_obj.record_state.cur === json_obj.record_state.all) {
			document.getElementById('jc_record_start').disabled = false;
			document.getElementById('jc_record_start').style.backgroundColor = '#4CAF50';
		};
		if (json_obj.record_state.nfs === true) {
			document.getElementById('jc_nfs_mount').disabled = true;
			document.getElementById('jc_nfs_mount').style.backgroundColor = 'gray';
		};
	}
	if (undefined != json_obj.algo_args) {
		if (document.getElementById('jc_test_a_track_th').value.trim() === '') {
			document.getElementById('jc_test_a_track_th').value = json_obj.algo_args.a_track_th;
		}
	}
}

//virt joystick
var joystickContainer;
var joystick;
let joystickPos = { x: 0, y: 0 };
let isDragging = false;
var g_update_pos_timeoutID;
function joystick_ctrl_init()
{
	joystickContainer = document.getElementById('joystick-container');
	joystick = document.getElementById('joystick');

	joystickContainer.addEventListener('mousedown', (e) => {
		isDragging = true;
		updateJoystickPosition(e);
		clearTimeout(g_update_pos_timeoutID);
		g_update_pos_timeoutID = setTimeout(joystick_pos_move, 100);
	});
	joystickContainer.addEventListener('mousemove', (e) => {
		if (isDragging) {
			updateJoystickPosition(e);
		}
	});
	joystickContainer.addEventListener('mouseup', () => {
		isDragging = false;
		resetJoystickPosition();
	});
	joystickContainer.addEventListener('mouseleave', (e) => {
		isDragging = false;
		resetJoystickPosition();
	});
}
function updateJoystickPosition(e)
{
	const rect = joystickContainer.getBoundingClientRect();
	const stick_rect = joystick.getBoundingClientRect();
	let newX = e.clientX - (rect.left+rect.width/2);
	let newY = e.clientY - (rect.top+rect.height/2);

	const maxRadius = rect.width/2;
	if (newX < -maxRadius) newX = -maxRadius;
	if (newX > maxRadius) newX = maxRadius;
	if (newY < -maxRadius) newY = -maxRadius;
	if (newY > maxRadius) newY = maxRadius;
	joystickPos = { x: newX, y: newY };
	joystick.style.transform = `translate(${joystickPos.x-stick_rect.width/2}px, ${joystickPos.y-stick_rect.height/2}px)`;
}
function resetJoystickPosition()
{
	joystickPos = { x: 0, y: 0 };
	joystick.style.transform = 'translate(-50%, -50%)';
	clearTimeout(g_update_pos_timeoutID);

	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "zt_ctrl",
			cmd: "zt_move",
			zt_move: {
				x: joystickPos.x,
				y: joystickPos.y,
			}
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function joystick_pos_move()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "zt_ctrl",
			cmd: "zt_move",
			zt_move: {
				x: joystickPos.x/5,
				y: -1*joystickPos.y/5,
			}
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
	g_update_pos_timeoutID = setTimeout(joystick_pos_move, 100);
}

function on_jc_zt_switch()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "zt_ctrl",
			cmd: "zt_enable",
			zt_enable: (document.getElementById('jc_zt_switch').checked) ? 1:0,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function jc_set_zoom()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "test_arg",
			cmd: "ctv_zoom",
			ctv_zoom: parseFloat(1000*document.getElementById('jc_test_zoom').value),
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_rec_offset_switch()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "test_arg",
			cmd: "rec_offset",
			rec_offset: (document.getElementById('jc_rec_offset_switch').checked) ? 1:0,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function jc_set_auto_track_th()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "test_arg",
			cmd: "a_track_th",
			a_track_th: parseInt(document.getElementById('jc_test_a_track_th').value),
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_auto_track_en()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "test_arg",
			cmd: "a_track_en",
			a_track_en: (document.getElementById('jc_auto_track_switch').checked) ? 1:0,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function on_jc_set_zoom_add()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "zoom_add",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_zoom_sub()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "zoom_sub",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_zoom_stop()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "zoom_stop",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_auto_zoom_en()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "a_zoom_en",
			a_zoom_en: (document.getElementById('jc_auto_zoom_switch').checked) ? 1:0,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_focus_add()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "focus_add",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_focus_sub()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "focus_sub",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_focus_stop()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "focus_stop",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_auto_focus_en()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "a_focus_en",
			a_focus_en: (document.getElementById('jc_auto_focus_switch').checked) ? 1:0,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_apert_add()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "apert_add",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_apert_sub()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "apert_sub",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_set_apert_stop()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "apert_stop",
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}
function on_jc_auto_apert_en()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "lens_ctrl",
			cmd: "a_apert_en",
			a_apert_en: (document.getElementById('jc_auto_apert_switch').checked) ? 1:0,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function on_jc_local_search_en()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "test_arg",
			cmd: "l_search_en",
			l_search_en: (document.getElementById('jc_local_search_switch').checked) ? 1:0,
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function on_page_load()
{
	canvas_init_draw();
	joystick_ctrl_init();

	var add_button = document.getElementById('jc_set_zoom_add');
	add_button.addEventListener('mouseup', function() {
		on_jc_set_zoom_stop();
	});
	var sub_button = document.getElementById('jc_set_zoom_sub');
	sub_button.addEventListener('mouseup', function() {
		on_jc_set_zoom_stop();
	});
	var add_button = document.getElementById('jc_set_focus_add');
	add_button.addEventListener('mouseup', function() {
		on_jc_set_focus_stop();
	});
	var sub_button = document.getElementById('jc_set_focus_sub');
	sub_button.addEventListener('mouseup', function() {
		on_jc_set_focus_stop();
	});
	var add_button = document.getElementById('jc_set_apert_add');
	add_button.addEventListener('mouseup', function() {
		on_jc_set_apert_stop();
	});
	var sub_button = document.getElementById('jc_set_apert_sub');
	sub_button.addEventListener('mouseup', function() {
		on_jc_set_apert_stop();
	});
}
